<template>
  <div class="user">
    <div class="page-head">
      <div class="page-title">用户列表</div>
      <div class="page-tool">
        <el-select
          v-model="state"
          placeholder="角色名称"
          class="tool-sel"
          clearable
        >
          <el-option
            v-for="item in roleSel"
            :key="item.role_id"
            :value="item.role_id"
            :label="item.name"
          ></el-option>
        </el-select>
        <search-input placeholder="用户名" @search="searchChange" />
        <div
          class="tool-btn"
          v-if="$permiss(btnPermiss, '新增')"
          @click="open('add')"
        >
          新 增
        </div>
      </div>
    </div>
    <div class="page-body">
      <div class="table_data">
        <el-scrollbar class="scroll-bar">
          <el-table :data="tableData" stripe row-key="user_id" class="my-table">
            <el-table-column
              width="20"
            />
            <el-table-column
              prop="name"
              label="用户名"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              prop="nick"
              label="昵称"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              prop="phone"
              label="手机号"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              prop="role_name"
              label="角色"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column label="操作" width="120" align="center">
              <template slot-scope="{ row }">
                <div class="operation-col">
                  <div
                    v-if="$permiss(btnPermiss, '修改')"
                    class="txt-btn ope-btn primary"
                    @click="open('edit', row)"
                  >
                    修改
                  </div>
                  <div
                    v-if="$permiss(btnPermiss, '删除')"
                    class="txt-btn error"
                    :class="{'grey notAllow': row.role_name == '超级管理员' }"
                    @click="doDelete(row)"
                  >
                    删除
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-scrollbar>
      </div>
      <div class="page-footer">
        <pagina-tion
          class="page-pager"
          v-show="total >= 0"
          :background="true"
          :total="total"
          :offset.sync="offset"
          :limit.sync="limit"
          @pagination="getChangePage"
        />
        <button class="page-button">确定</button>
      </div>
    </div>
    <!-- 新增和修改弹框 -->
    <el-dialog
      :visible.sync="model.visible"
      width="450px"
      :title="model.type === 'add' ? '新增用户' : '修改用户'"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="dialog-body">
        <el-form
          ref="form"
          :model="form"
          label-width="110px"
          label-position="left"
        >
          <el-form-item label="用户名" class="required">
            <el-input
              name="username"
              :disabled="model.type !== 'add'"
              v-model="form.name"
              v-validate="'required|username'"
              @keydown.native="keydown($event)"
            />
            <div v-show="errors.has('username')" class="el-form-item__error">
              {{ errors.first("username") }}
            </div>
          </el-form-item>
          <el-form-item label="昵称">
            <el-input v-model="form.nick" />
          </el-form-item>
          <el-form-item label="手机号" class="required">
            <el-input
              name="phone"
              v-model="form.phone"
              v-validate="'required|phone'"
              @keydown.native="keydown($event)"
            />
            <div v-show="errors.has('phone')" class="el-form-item__error">
              {{ errors.first("phone") }}
            </div>
          </el-form-item>
          <el-form-item label="角色" label-position="left" class="required">
            <el-select
              class="form-sel"
              v-model="form.role_id"
              name="role"
              placeholder="请选择角色"
              v-validate="'required'"
            >
              <el-option
                v-for="item in roleSel"
                :key="item.role_id"
                :label="item.name"
                :value="item.role_id"
                :disabled="item.name === '超级管理员'"
              />
            </el-select>
            <div v-show="errors.has('role')" class="el-form-item__error">
              {{ errors.first("role") }}
            </div>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="close">取 消</el-button>
        <el-button type="primary" @click="submit">保 存</el-button>
      </span>
    </el-dialog>
    <!-- 删除弹窗 -->
    <el-dialog
      :visible.sync="visibility"
      width="430px"
      height="100px"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="dialog-content comfirm-body">
        <img class="comfirm-ico" src="~assets/img/warning.png" />
        <div class="comfirm-txt">
          <div>确定删除该条数据？</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="visibility = false">取 消</el-button>
        <el-button type="primary" @click="userDelete">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { format } from "silly-datetime";
import * as api from "@/api";
import { limit, middleLimit } from "@/consts/consts";
import { userFormKey } from "@/consts/formKey";
export default {
  data() {
    return {
      btnPermiss: [],
      limit: document.body.clientHeight>= 770 ? limit : middleLimit,
      total: 0,
      offset: 0,
      tableData: [],
      format,
      search: "",
      roleSel: [],
      filterRole: [],
      model: {
        type: "add",
        visible: false,
      },
      user_id: "",
      form: { ...userFormKey },
      visibility: false,
      state: "",

    };
  },

  watch: {
    state() {
      this.userList();
    },
  },
  methods: {
    open(type, row = null) {
      this.$validator.reset();
      this.model.type = type;
      if (row) {
        for (const k in userFormKey) {
          this.form[k] = row[k];
        }
        this.user_id = row.user_id;
      }
      this.model.visible = true;
    },
            
    keydown(event){
      if (event.keyCode == 32) {
        event.returnValue = false
      }
    },

    doDelete(row) {
      if (row.role_name == "超级管理员") {
        return false;
      }
      this.user_id = row.user_id;
      this.visibility = true;
    },

    jump(row) {
      this.$router.push(`/license/${row.user_id}`);
    },

    getChangePage(val) {
      this.offset = val.offset;
      this.userList();
    },

    searchChange(e) {
      this.offset = 0
      this.search = e;
      this.userList();
    },

    provinceChange(e) {
      this.form.city = "";
      this.cityList = [];
      this.areaList(e);
    },

    close() {
      this.model.visible = false;
      this.form = { ...userFormKey };
    },

    submit() {
      this.$validator.validateAll().then((valid) => {
        if (valid) {
          if (this.form.nick) {
            let reg = /^[\u4E00-\u9FA5]{1,8}$/.test(this.form.nick);
            if (!reg) {
              this.$message.warning("昵称请输入8位以内中文");
              return false;
            }
          }
          this.addOrEdit();
        } else {
          this.$message.warning("有信息未填写正确");
        }
      });
    },

    // 角色列表
    async roleList() {
      const { code, data } = await api.role(this).roleList({
        offset: -1,
        limit: -1
      });
      if (code === 0) {
        this.roleSel = data;
        this.filterRole = data.filter((item) => item.name !== "超级管理员");
      }
    },

    // 机构列表
    async userList() {
      const { code, data, total } = await api.user(this).userList({
        offset: this.offset,
        limit: this.limit,
        name: this.search,
        role_id: this.state,
      });
      if (code === 0) {
        this.tableData = data;
        this.total = total;
      }
    },

    async addOrEdit() {
      let fn = this.model.type === "add" ? "userAdd" : "userUpdate";
      const { code } = await api.user(this)[fn](this.form, this.user_id);
      if (code === 0) {
        this.$message.success("操作成功");
        this.close();
        this.userList();
      }
    },

    async userDelete() {
      const { code } = await api.user(this).userDelete(this.user_id);
      if (code === 0) {
        this.$message.success("操作成功");
        this.user_id = "";
        this.visibility = false;
        if (this.total % this.limit === 1) {
          if (this.offset >= this.limit) {
            this.offset -= this.limit;
          }
        }
        this.userList();
      }
    },
  },
  created() {
    this.roleList();
    this.userList();
    let permission = JSON.parse(localStorage.getItem("permission"));
    let curMenu = permission.find(item => item.txt === "用户管理")
    this.btnPermiss = curMenu.btns
  },

};
</script>

<style lang="stylus">
.User {
  
}
</style>